<?php
class Pageley_Log_Factory {
	private $appenders;
	private $levels;
	private $loggers;

	private static $instance;

	public static function getInstance() {
		if(self::$instance === null) {
			self::$instance = new Pageley_Log_Factory();
		}
		return self::$instance;
	}

	private function __construct() {
		$this->loggers = new Pageley_Util_ArrayMap();
		$this->levels = new Pageley_Util_ArrayMap(array(
			"Pageley" => Pageley_Log_Level::$INFO
		));
	}

	public function setAppenders($appenders) {
		$this->appenders = $appenders;
	}

	public function setLevels($levels) {
		$this->levels = $levels;
		$this->loggers = new Pageley_Util_ArrayMap();
	}

	private function getLevel($sourceClass) {
        $bestMatch = null;
		foreach($this->levels as $package => $level) {
			if(Pageley_Util_String::startsWith($sourceClass, $package) && ($bestMatch === null || 
                    Pageley_Util_String::length($package) > Pageley_Util_String::length($bestMatch))) {
                $bestMatch = $package;
			}
		}
		return $this->levels->get($bestMatch);
	}

	public function getLogger($object) {
        if(is_object($object)) {
            $sourceClass = get_class($object);
        } else {
            $sourceClass = $object;
        }
		$logger = $this->loggers->get($sourceClass);
		if($logger === null) {
			$level = $this->getLevel($sourceClass);
			if($level === null) {
				$level = Pageley_Log_Level::$INFO;
			}
			if($this->appenders === null) {
				$this->appenders = new Pageley_Util_ArrayMap(new Pageley_Log_ConsoleAppender());
			}
			$logger = new Pageley_Log_Logger($sourceClass, $level, $this->appenders);
			$this->loggers->put($sourceClass, $logger);
		}
		return $logger;
	}
}